import pymysql
from common.handle_conf import conf


class HandleDb:

    def __init__(self):
        self.con = pymysql.connect(
            host=conf.get('mysql', 'host'),
            port=conf.getint('mysql', 'port'),
            user=conf.get('mysql', 'user'),
            password=conf.get('mysql', 'password'),
            charset='utf8',
            # cursorclass = pymysql.cursors.DictCursor   #想要返回的数据是字典格式的就带这个，单独一条就是字典，多的话就是列表嵌套字典
        )
    def find_all(self,sql):
        '''查询所有的数据'''
        # with self.con as cur:
        #     cur.execute(sql)
        # res = cur.fetchall()
        # cur.close()
        # return res

        cur = self.con.cursor()
        cur.execute(sql)
        res = cur.fetchall()
        cur.close()
        return res  #和上面的效果是一样的，0.9.3之后的pymysql


    def find_one(self,sql):
        '''查询一条数据'''
        with self.con as cur:
            cur.execute(sql)
        res = cur.fetchone()
        cur.close()
        return res

    def find_count(self,sql):
        '''sql执行完之后，返回的数据条数'''
        with self.con as cur:
            res  = cur.execute(sql)
        cur.close()
        return res

    def __del__(self):
        self.con.close()

if __name__ == '__main__':
    sql = 'SELECT * FROM future.member limit 5'

    db =  HandleDb()
    res = db.find_one(sql)
    res1 = db.find_count(sql)
    res2 = db.find_all(sql)
    print(res)   #（1, '檬檬', '25F9E794323B453885F5181F1B624D0B', '18612351112', 1, Decimal('32850668.27'), datetime.datetime(2023, 2, 14, 12, 15, 12))
    print(res1)  #5
    print(res2)